package com.atmilan.quartz.utils.source;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

import com.atmilan.quartz.constant.enums.StockAreaTempEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.atmilan.quartz.constant.enums.BarCodeEnum;
import com.atmilan.quartz.constant.enums.CategoryTypeEnum;
import com.atmilan.quartz.constant.enums.ProductTypeEnum;
import com.atmilan.quartz.model.dto.crmeb.StoreProductCrmebRequest;
import com.atmilan.quartz.model.entity.buyer.Supplier;
import com.atmilan.quartz.model.entity.crmeb.CategoryMatch;
import com.atmilan.quartz.model.entity.crmeb.StoreBrand;
import com.atmilan.quartz.model.entity.crmeb.StoreProductAttr;
import com.atmilan.quartz.model.entity.im.ImProduct;
import com.atmilan.quartz.model.entity.im.ImProductSku;
import com.atmilan.quartz.model.result.PriceResult;
import com.atmilan.quartz.service.ICategoryMatchService;
import com.atmilan.quartz.service.IStoreBrandService;
import com.atmilan.quartz.service.ISupplierService;
import com.atmilan.quartz.sync.push.crmeb.domain.StoreProductAttrValueRequest;
import com.atmilan.quartz.sync.push.crmeb.enums.CrmebMerchantEnums;
import com.atmilan.quartz.utils.PriceUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

/**
 * 处理源数据转换和计算相关信息
 * @Description: 
 * @author daigb
 * @date 2021-03-05
 */
@Service
public class SourceImProductUtil {
    @Autowired
    IStoreBrandService storeBrandService;
    @Autowired
    ICategoryMatchService categoryMatchService;
    @Autowired
    ISupplierService supplierService;
    @Autowired
    PriceUtil priceUtil;

    // 临时处理固定原价
    List<String> otPrice2000 = Arrays.asList("1018010906", "1018016300", "1018011906", "10180119", "101801", "1146975", "10180109000", "10180103600", "10180103806", "10180199000", "10180103600", "10180109600");
    List<String> otPrice1600 = Arrays.asList("10161413000", "1016140906002", "10161413600", "10161413600562", "1016140906", "10161495000");
    List<String> otPrice3200 = Arrays.asList("10160915600", "1016091506", "1016091506", "1016091906", "10160909600", "10160909600");
    List<String> otPrice1880 = Arrays.asList("TEDGIRL", "10161513", "10160713", "TEDDY1", "TDGIRL1", "10160516");
    List<String> otPrice1250 = Arrays.asList("TEDDY2", "10860303");
    
    /**
     * 构建DO对象
     * @Description:  
     * @author daigb 
     * @param @param product
     * @param @param productSkus
     * @param @return
     * @return StoreProductRequest
     * @throws
     */
    public StoreProductCrmebRequest buildImProduct(ImProduct imProduct, List<ImProductSku> productSkus) {
        // 主商品对象
        StoreProductCrmebRequest productRequest = null;
        try {
            JSONArray gallery = JSONArray.parseArray(imProduct.getImages());
            ImProductSku minSku = productSkus.stream().min(Comparator.comparing(ImProductSku :: getSalePrice)).get();
            // 成本价
            PriceResult priceResult = priceUtil.eur2Rmb(minSku.getSalePrice());
            BigDecimal erpPrice = priceResult.getPrice();
            // 市场价
            BigDecimal retailPrice = Optional.ofNullable(minSku.getRetailPrice()).orElse(minSku.getSalePrice());
            if(otPrice2000.contains(imProduct.getDesignerId())) {
            	retailPrice = new BigDecimal("2000");
            	productSkus.forEach(o -> o.setRetailPrice(new BigDecimal("2000")));
            } else if(otPrice1600.contains(imProduct.getDesignerId())) {
            	retailPrice = new BigDecimal("1600");
            	productSkus.forEach(o -> o.setRetailPrice(new BigDecimal("1600")));
            } else if(otPrice3200.contains(imProduct.getDesignerId())) {
            	retailPrice = new BigDecimal("3200");
            	productSkus.forEach(o -> o.setRetailPrice(new BigDecimal("3200")));
            } else if(otPrice1880.contains(imProduct.getDesignerId())) {
            	retailPrice = new BigDecimal("1880");
            	productSkus.forEach(o -> o.setRetailPrice(new BigDecimal("1880")));
            } else if(otPrice1250.contains(imProduct.getDesignerId())) {
            	retailPrice = new BigDecimal("1250");
            	productSkus.forEach(o -> o.setRetailPrice(new BigDecimal("1250")));
            }
            // 销售价(计算后)
            BigDecimal adjustPrice = erpPrice;
            // 成本价(计算后)
            BigDecimal adjustCost = erpPrice;
            // 大于或小于指定折扣, 原价置空
            BigDecimal otPriceRmb = priceUtil.eur2Rmb(retailPrice).getPrice();
       	 	boolean discount20 = otPriceRmb.compareTo(BigDecimal.ZERO) == 0 ? false : new BigDecimal("2").compareTo(adjustPrice.divide(otPriceRmb, 2, RoundingMode.HALF_UP)) <= 0;
       	 	boolean discount1 = otPriceRmb.compareTo(BigDecimal.ZERO) == 0 ? false : new BigDecimal("0.1").compareTo(adjustPrice.divide(otPriceRmb, 2, RoundingMode.HALF_UP)) >= 0;
            if(discount20 || discount1) {
            	retailPrice = BigDecimal.ZERO;
            }
            
            // 品牌对应 (IM标准商品 type = 1)
            StoreBrand storeBrand = storeBrandService.getOne(Wrappers.<StoreBrand>lambdaQuery()
                    .eq(StoreBrand :: getId, imProduct.getBrandId())
                    .eq(StoreBrand :: getType, ProductTypeEnum.INSIDE)
                    .last("LIMIT 1")
                    );
            storeBrandService.unMatchBrand(storeBrand,imProduct.getBrandId().toString(),null,ProductTypeEnum.INSIDE);
            // 5429 IM标准其他品牌
            if(null == storeBrand){
                storeBrand = storeBrandService.getById(5429);
            }

            /***** 处理对象构建 *******/
            String barCode = BarCodeEnum.IM.getCode() + imProduct.getProductId().toString();
            List<StoreProductAttr> attrList = new ArrayList<StoreProductAttr>();
            List<StoreProductAttrValueRequest> attrValueList = new ArrayList<StoreProductAttrValueRequest>();
            Integer tempId = 2;
            for(ImProductSku sku : productSkus) {
                // 成本价
                BigDecimal erpSkuPrice = priceUtil.eur2Rmb(sku.getSalePrice()).getPrice();
                // 市场价
                BigDecimal retailSkuPrice = sku.getSalePrice();
                // 销售价(计算后)
                BigDecimal adjustSkuPrice = erpSkuPrice;
                // 成本价(计算后)
                BigDecimal adjustSkuCost = erpSkuPrice;
                // 大于或小于指定折扣, 原价置空
                BigDecimal otPriceValRmb = priceUtil.eur2Rmb(retailSkuPrice).getPrice();
           	 	boolean discountVal20 = otPriceValRmb.compareTo(BigDecimal.ZERO) == 0 ? false : new BigDecimal("2").compareTo(adjustSkuPrice.divide(otPriceValRmb, 2, RoundingMode.HALF_UP)) <= 0;
           	 	boolean discountVal1 = otPriceValRmb.compareTo(BigDecimal.ZERO) == 0 ? false : new BigDecimal("0.1").compareTo(adjustSkuPrice.divide(otPriceValRmb, 2, RoundingMode.HALF_UP)) >= 0;
                if(discountVal20 || discountVal1) {
                	retailSkuPrice = BigDecimal.ZERO;
                }
                // value对象
                StoreProductAttrValueRequest storeProductAttrValue = new StoreProductAttrValueRequest();
                storeProductAttrValue.setSourceSkuId(sku.getItemId());
                storeProductAttrValue.setSuk(sku.getSize());
                storeProductAttrValue.setStock(sku.getQty());
                storeProductAttrValue.setPrice(adjustSkuPrice);
                if(gallery.size() > 0) {
                    storeProductAttrValue.setImage(gallery.get(0).toString());
                }
                storeProductAttrValue.setCost(adjustSkuCost);
                storeProductAttrValue.setSourceCost(erpSkuPrice);
                storeProductAttrValue.setBarCode(barCode);
                storeProductAttrValue.setOtPrice(retailSkuPrice);
                
                LinkedHashMap<String, String> linkedMap = new LinkedHashMap<>();
                if (StringUtils.isNotBlank(sku.getSize())) {
                    linkedMap.put("尺寸", sku.getSize());
                }
                storeProductAttrValue.setAttrValue(linkedMap);
                if (sku.getShippingAddress().equals("中国")) {
                    tempId = StockAreaTempEnum.CN.getTempId();
                } else if (sku.getShippingAddress().equals("中国澳门") || sku.getShippingAddress().equals("中国香港")) {
                    tempId = StockAreaTempEnum.HK.getTempId();
                } else {
                    tempId = StockAreaTempEnum.EUR.getTempId();
                }
                storeProductAttrValue.setTempId(tempId);
                attrValueList.add(storeProductAttrValue);
                // attr对象
                if(CollectionUtils.isEmpty(attrList)) {
                    StoreProductAttr attr = new StoreProductAttr();
                    attr.setProductId(sku.getProductId());
                    attr.setAttrName("尺寸");
                    attr.setAttrValues(sku.getSize());
                    attr.setBarCode(barCode);
                    attrList.add(attr);
                } else {
                    StoreProductAttr attr = attrList.get(0);
                    attr.setAttrValues(attr.getAttrValues() + "," + sku.getSize());
                }
            }
            
            productRequest = new StoreProductCrmebRequest();
            productRequest.setExchangeRate(priceResult.getExchangeRate());
            productRequest.setAttr(attrList);
            productRequest.setAttrValue(attrValueList);
            // 强制写一个 商户id 作为buyer商品标识标识
            productRequest.setMerId(CrmebMerchantEnums.IM.getMerchantId());
            productRequest.setContent(imProduct.getDescription());
            productRequest.setKeyword(imProduct.getDesignerId());
            productRequest.setStoreInfo(imProduct.getDescription());
            productRequest.setStoreName(imProduct.getName());
            if(null != storeBrand) {
                productRequest.setBrandId(storeBrand.getId());
                productRequest.setBrandName(storeBrand.getEnName());
            }
            productRequest.setPrice(adjustPrice);
            productRequest.setOtPrice(retailPrice);
            productRequest.setCost(adjustCost);
            productRequest.setSourceCost(erpPrice);
            productRequest.setPromoteFlag(false);
            productRequest.setErpPromFlag(true);
            productRequest.setTempId(tempId);

            // 供应商
            Supplier supplier = supplierService.getOne(Wrappers.<Supplier>lambdaQuery()
                    .eq(Supplier :: getBarcode, BarCodeEnum.IM.getCode())
                    .last("LIMIT 1")
                    );
            if(null != supplier) {
                productRequest.setSuppliersId(supplier.getId());
                productRequest.setSuppliersName(supplier.getSuppliersName());
            }
            productRequest.setBarCode(barCode);
            // 分类 (IM type = 1)
            CategoryMatch categoryMatch = categoryMatchService.getOne(Wrappers.<CategoryMatch>lambdaQuery()
                    .eq(CategoryMatch :: getType, CategoryTypeEnum.XUNWU)
                    .eq(CategoryMatch :: getId, imProduct.getCategoryId())
                    .last("LIMIT 1")
                    );
            // (IM标准)
            categoryMatchService.unMatchCategory(categoryMatch,imProduct.getCategoryId(),null,null,CategoryTypeEnum.XUNWU);
            // 复制重量
            if(null != categoryMatch) {
//            	CategoryMatch supCategoryMatch = categoryMatchService.getById(categoryMatch.getCategoryId());
            	categoryMatch.setWeight(categoryMatch.getWeight());
            }
            Integer categoryId = null != categoryMatch ? categoryMatch.getId() : 1859;
            productRequest.setCateId(categoryId);
            productRequest.setCateIds(Arrays.asList(categoryId));
            productRequest.setWeight(null != categoryMatch ? categoryMatch.getWeight() : BigDecimal.ONE);
            if(gallery.size() > 0) {
                productRequest.setImage(gallery.get(0).toString());
                productRequest.setSliderImage(gallery.toJSONString());
            }
            productRequest.setIsShow(true);
            productRequest.setSpecType(true);
            productRequest.setIsEurope(ProductTypeEnum.IM.getCode());
            productRequest.setUnitName("件");
            productRequest.setComposition(imProduct.getComposition());
            productRequest.setDimension(imProduct.getDimension());
            productRequest.setColorCode(imProduct.getColorCode());
            productRequest.setSeasonCode(imProduct.getSeasonCode());
            
            productRequest.setLastPushTime(new Date());
            productRequest.setAddTime(Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return productRequest;
    }
    
}
